import React, {Component} from 'react'
import {withRouter} from 'react-router-dom'
import { Modal} from 'antd'
import {formateDate} from '../../utils/dateUtils'
import memoryUtils from '../../utils/memoryUtils'
import storageUtils from '../../utils/storageUtils'
import menuList from '../../config/menuConfig'
import LinkButton from '../link-button'
import './header.less'
import {reqGetWeather} from '../../api'

class Header extends Component {

  constructor(props) {
    super(props);
    this.state = {
        currentTime: formateDate(Date.now()), // 当前时间字符串
        dayPictureUrl: '', // 天气图片url
        weather: '', // 天气的文本
    };
  }
componentDidMount() {
  this.getTime()
  this.getWeather()
}
componentWillUnmount() {
  clearInterval(this.intervalId)
}
  //退出登录
  logout=()=>{
    Modal.confirm({
      content:"确定退出吗",
      okText:"确认",
      cancelText:"取消",
      onOk:()=>{
          storageUtils.removeUser()
        memoryUtils.user = {}
        this.props.history.replace('/login')
      }
    })
  }
  //获取天气
  getWeather =async () => {
    // 调用接口请求异步获取数据
   let res= await reqGetWeather()
  //  console.log(res);
   let weather = res.lives[0].weather
    // // 更新状态
    this.setState({weather})
  }
  //获取时间
  getTime = () =>{
    this.intervalId= setInterval(() => {
      let currentTime= formateDate(Date.now())
        this.setState({
          currentTime
        })
    }, 1000);
  }

  //获取title
  getTitle=()=>{
    let title="";
    menuList.forEach((item)=>{
      if(item.key==this.props.location.pathname){
        title=item.title
      }else if (item.children){
        if(this.props.location.pathname.indexOf('/product')===0){
          title="商品管理"
        }else{
          let citem = item.children.find((ditem)=>{ return ditem.key==this.props.location.pathname})
          if(citem){
            title = citem.title
          }
        }
      }
    })
    return title
  } 
  
  render() {
    const {currentTime, dayPictureUrl, weather} = this.state
    const username = memoryUtils.user.username
    // 得到当前需要显示的title
    const title = this.getTitle()
    // const title = "shouye"
    return (
      <div className="header">
        <div className="header-top">
          <span>欢迎, {username}</span>
          <LinkButton onClick={this.logout}>退出</LinkButton>
        </div>
        <div className="header-bottom">
          <div className="header-bottom-left">{title}</div>
          <div className="header-bottom-right">
            <span>{currentTime}</span>
            {/* <img src={dayPictureUrl} /> */}
            <span style={{marginLeft:"5px"}}>{weather}</span>
          </div>
        </div>
      </div>
    )
  }
}


export default withRouter(Header)